Aliases in Ecto
In Ecto, aliases are used to set shorter names for modules, allowing you to reference and access everything inside them more easily. Essentially, an alias acts as a variable that refers to a module, simplifying code by reducing the need to type the full module name each time. Aliases can be used in both modules and Ecto queries.
Using Aliases in modules,
Consider the following example module, SqlEcto.Hr, which is created for project functionalities and includes two aliases: HR.Country and HR.Repo.

In this module,
alias HR.Countryallows us to use Country instead ofHR.Country.alias HR.Repoallows us to useRepoinstead ofHR.Repo.
This practice helps developers work more efficiently by using shorter, more convenient names instead of the full module names.
Using Aliases in Ecto Queries,
HR.Country
|> select([c], c)
|> HR.Repo.all()
In this query:
[c]serves as the reference variable (binding) for HR.Country.[c]representsHR.Countrythroughout the query.
You can choose any name for the binding. For instance:
HR.Country
|> select([country], country)
|> HR.Repo.all()
In this example, country is used as the binding instead of c. It's important to note that the binding should be placed inside a list; otherwise, it will result in an error. This ensures that the output of the query will be a list.

retrieve specific fields,
HR.Country
|> select([c], [c.first_name, c.email])
|> HR.Repo.all()
This query retrieves only the first_name and email fields from HR.Country.
Using aliases in both modules and Ecto queries helps streamline your code, making it more readable and easier to manage.